//
//  BERxObservableValue.swift
//  BasicExtensions
//
//  Created by 范晓鑫 on 2023/1/28.
//

import RxSwift

///可获取ObservableType的最后一个值
@propertyWrapper
class ObservedValue<T: ObservableType> {
    var disposeBag = DisposeBag()
    var value: T
    var lastValue: T.Element?
    init(wrappedValue: T) {
        self.value = wrappedValue
        self.observeValue()
    }
    /// 观察值变化
    fileprivate func observeValue() {
        self.value.subscribe(onNext: { [weak self] v in
            self?.lastValue = v
        }).disposed(by: self.disposeBag)
    }
    var wrappedValue: T {
        get {
            return self.value
        }
        set {
            self.disposeBag = DisposeBag()
            self.value = newValue
            self.observeValue()
        }
    }
    /// 提供值访问
    var projectedValue: T.Element? {
        return self.lastValue
    }
}
///将普通的属性标记为可观察属性
@propertyWrapper
class ObservableValue<T> {
    let observable: BehaviorSubject<T>
    var value: T
    init(wrappedValue: T) {
        self.value = wrappedValue
        self.observable = .init(value: wrappedValue)
    }
    var wrappedValue: T {
        get {
            return self.value
        }
        set {
            self.value = newValue
            self.observable.onNext(newValue)
        }
    }
    /// 提供值访问
    var projectedValue: Observable<T> {
        return self.observable.asObservable()
    }
}

